package com.cavy.platform.server.validator;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.repository.PipelineRepository;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 验证pipeline名称是否重复
 */
public class PipelineNameNotRepeatValidator implements ConstraintValidator<PipelineNameNotRepeat, PipelineNameNotRepeatData> {
    private PipelineRepository bean;

    @Override
    public void initialize(PipelineNameNotRepeat notRepeatPluginName) {
        bean = BeansProvider.getBean(PipelineRepository.class);
    }

    @Override
    public boolean isValid(PipelineNameNotRepeatData dto, ConstraintValidatorContext context) {
        int count = bean.countByName(dto.getWorkspace(), dto.getProjectName(), dto.getPipelineName());
        if (count > 0) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addPropertyNode(dto.getPipelinePropertyNode()).addConstraintViolation();
            return false;
        }
        return true;
    }
}
